import sys
import os
import time
import hashlib
import datetime
import decimal
import random
import shutil
import chardet
# from xpinyin import Pinyin
from dateutil.relativedelta import relativedelta
from dateutil.parser import parse


####################操作系统、文件系统分隔符####################
def test():
	"""
	测试用，未实际应用
	"""
	ostype = sys.platform
	if "win" in ostype:
		print("Windows环境！")
	elif "linux" in ostype:
		print("Linux环境！")

	cur_sep = os.path.sep
	print("文件分隔符：%s" % cur_sep)


def checkLinuxOrWindows():
	env = -1
	ostype = sys.platform
	if "win" in ostype:
		env = 2
	elif "linux" in ostype:
		env = 1
	return env


#########################时间函数####################
def get_current_time():
	return time.strftime('%Y-%m-%d %X', time.localtime(time.time()))


def get_current_timestamp():
	return time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))


def get_time(time_obj):
	if isinstance(time_obj, datetime.datetime):
		return time_obj.strftime("%Y-%m-%d %H:%M:%S")
	elif isinstance(time_obj, str):
		return datetime.datetime.strptime(time_obj, "%Y-%m-%d %H:%M:%S")


def get_time_hour(time_obj):
	if isinstance(time_obj, datetime.datetime):
		return time_obj.strftime("%Y-%m-%d %H:00:00")
	elif isinstance(time_obj, str):
		return datetime.datetime.strptime(time_obj, "%Y-%m-%d %H:00:00")


def get_time_day(time_obj):
	if isinstance(time_obj, datetime.datetime):
		return time_obj.strftime("%Y-%m-%d")
	elif isinstance(time_obj, str):
		date_string = time_obj.split(" ")[0]  	# 分离出日期部分
		return datetime.datetime.strptime(date_string, "%Y-%m-%d")


def get_time_week(time_obj):
	if isinstance(time_obj, datetime.datetime):
		return time_obj.strftime("%Y-%VW")
	elif isinstance(time_obj, str):
		return datetime.datetime.strptime(time_obj, "%Y-%VW")


def get_time_month(time_obj):
	if isinstance(time_obj, datetime.datetime):
		return time_obj.strftime("%Y-%m")
	elif isinstance(time_obj, str):
		return datetime.datetime.strptime(time_obj, "%Y-%m")


def get_time_quarter(time_obj):
	if isinstance(time_obj, datetime.datetime):
		month = int(time_obj.strftime("%m"))
		return time_obj.strftime("%Y") + "-" + str(int((month - 1) / 3) + 1) + "Q"
	elif isinstance(time_obj, str):
		month = int(datetime.datetime.strptime(time_obj, "%m"))
		return datetime.datetime.strptime(time_obj, "%Y") + "-" + str(int((month - 1) / 3) + 1) + "Q"


def get_time_year(time_obj):
	if isinstance(time_obj, datetime.datetime):
		return time_obj.strftime("%Y")
	elif isinstance(time_obj, str):
		return datetime.datetime.strptime(time_obj, "%Y")


def get_date_from_week(year, week):
	"""
	year int类型
	week int类型
	return  datetime.date
	"""
	start_date = datetime.date(year, 1, 1) + relativedelta(weeks=week)
	end_date = start_date + datetime.timedelta(days=6)
	print(start_date, end_date)
	return start_date, end_date


def get_interview(start_time, end_time):
	"""
	:param start_time: "2020-05-05 23:56:45"
	:param end_time: "2020-05-06 00:00:31"
	:return:
	"""
	date1 = parse(start_time)			# 'datetime.datetime'
	date2 = parse(end_time)				# 'datetime.datetime'
	result = (date2 - date1).total_seconds()
	print(result)


def get_interview_v2(start_time, end_time):
	"""
	:param start_time: "2020-05-05 23:56:45"
	:param end_time: "2020-05-06 00:00:31"
	:return:
	"""
	date1 = parse(start_time)
	date2 = parse(end_time)
	return get_dur_time(date1, date2)


def get_dur_time(start, end):
	"""
	返回间隔时间：
	Args:
		start: 开始时间<datetime.datetime>
		end: 结束时间<datetime.datetime>
	Returns:
		返回间隔时间(ms)
	"""
	return (end - start).seconds * 1000 + (end - start).microseconds / 1000
#测试get_dur_time函数
	"""
	import datetime
	import time
	
	start_time = datetime.datetime.now()
	print(start_time)
	time.sleep(2)
	end_time = datetime.datetime.now()
	print(end_time)
	print(get_dur_time(start_time, end_time))
	"""

def isoformat(time):
	'''
	将datetime或者timedelta对象转换成ISO 8601时间标准格式字符串
	:param time: 给定datetime或者timedelta
	:return: 根据ISO 8601时间标准格式进行输出
	'''
	if isinstance(time, datetime.datetime): # 如果输入是datetime
		return time.isoformat();
	elif isinstance(time, datetime.timedelta): # 如果输入时timedelta，计算其代表的时分秒
		hours = time.seconds / 3600
		minutes = time.seconds % 3600 / 60
		seconds = time.seconds % 3600 % 60
		return '%sD%sH%sM%sS' % (time.days, hours, minutes, seconds) # 将字符串进行连接


# 字符串'2022-01-20T14:00:00Z'转时间戳
# 2023-09-25T22:54:19.993Z
# 2023-08-29 17:00:01+00:00
#TODO 临时方案
def str2timestamp(time_str):
	#return datetime.datetime.strptime(time_str, "%Y%m%dT%H%M%SZ")
	#return time.strftime('%Y-%m-%d %X', time.localtime(time.time()))
	#return datetime.datetime.strptime(time_str, format)
	time_str = time_str.split('.')[0]
	time_str = time_str.split('+')[0]
	time_str = time_str.replace('T', ' ')
	time_str = time_str.replace('Z', ' ')
	print("过滤时间戳！")
	print(time_str)
	return time_str


# 时间加减
# 开始时间 + 小时时间，如：2022-11-30 09:00:00 -> 2022-11-30 10:00:00
def get_end_time_from_start_time(start_time, hours):
	time_format_str = "%Y-%m-%d %H:%M:%S"
	if isinstance(start_time, datetime.datetime):
		time_obj = start_time
	elif isinstance(start_time, str):
		time_obj = datetime.datetime.strptime(start_time, time_format_str)
	return  (time_obj + datetime.timedelta(hours=hours)).strftime(time_format_str)


# 其他:
# datetime转字符串
def datetime_2_str():
	now = datetime.now()
	date = now.strftime('%Y-%m-%d %H:%M:%S')
	print(date)

# 字符串转datetime
def str_2_datetime():
	datestr = "2020-05-06 18:42:26"
	date = datetime.strptime(datestr, "%Y-%m-%d %H:%M:%S")
	print(date)
	print(type(date))

# 时间戳转datetime
def timestamp_2_datetime():
	timestamp = 1588761521787 / 1000
	date = datetime.fromtimestamp(timestamp)
	print(date)

# 得到datetime对象
def genDateTimeObj():
	date = datetime(2020, 4, 19, 15, 30)
	print(date)
	print(type(date))


#########################字符串操作相关#########################
#清除字符串中斜线及回车换行符
def clean(s):
	return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "").replace(",", "，")

#Hash值
def hash_digest(s):
	return "h_%s" % hashlib.sha256(s).hexdigest()

#获取汉字字符串中所有汉字拼音首字母
'''
def get_initial_letter(ch):
	if ch=="":
		return ""

	#get rid of the "，" in ch
	ch = ch.replace("，", "").replace(",", "").replace("、", "")

	pin = Pinyin()	
	test = pin.get_pinyin(ch, "-")

	ret_str = ""
	pinyin_arr = test.split("-")
	for item in pinyin_arr:
		ret_str += item[0]
	
	return ret_str
'''

#获取字典变量指定key的值
def get_val(dict, key):
	if key in dict.keys() and clean(dict[key]) != "缺":
		return clean(dict[key])
	else:
		return ""

def get_name_gender_birthday(s):
	arr = s.split(" ")
	ret_arr = []
	for item in arr:
		if item.strip() != "":
			ret_arr.append(item)
	#it's a triky here
	while len(ret_arr) < 3:
		ret_arr.append(" ")

	return ret_arr


# 字符串转整数（支持整数和浮点数格式字符串）
def str_to_int(str):
    try:
        int(str)
        return int(str)
    except ValueError: #报类型错误，说明不是整型的
        try:
            float(str) #用这个来验证，是不是浮点字符串
            return int(float(str))
        except ValueError:  #如果报错，说明即不是浮点，也不是int字符串。   是一个真正的字符串
            return "False"


# 字符串转浮点数
def str_to_float(number):
    try:
        return float(number)
    except:
        return number


# 转化变量为字符串
def obj_to_str(obj):
	"""
	obj对象转化为带双引号的字符串
	:param obj:
	:return:
	"""
	# print(obj)
	# print(type(obj))
	if isinstance(obj, str):
		return '"%s"' % obj
	elif isinstance(obj, int):
		return '"%d"' % obj
	elif isinstance(obj, float):
		return '"%.6f"' % obj
	elif isinstance(obj, decimal.Decimal):
		return '"%.6f"' % obj
	elif isinstance(obj, datetime.datetime):
		return '"%s"' % obj

	# return None
	return '""'


# 转化变量为字符串
def obj_to_strV2(obj):
	# print(obj)
	# print(type(obj))
	if isinstance(obj, str):
		return '%s' % obj
	elif isinstance(obj, int):
		return '%d' % obj
	elif isinstance(obj, float):
		return '%.6f' % obj
	elif isinstance(obj, decimal.Decimal):
		return '%.6f' % obj
	elif isinstance(obj, datetime.datetime):
		return '%s' % obj

	# return None
	return ''


# 按照给定的变量类型进行转化
def obj_to_example_var(example_obj, var_obj):
	# print("obj_to_example_var", example_obj, var_obj)
	# print(obj)
	# print(type(obj))
	if isinstance(example_obj, str):
		return '%s' % var_obj
	elif isinstance(example_obj, int):
		#return int(var_obj)
		return float(var_obj)        # 实际场景考虑兼容情况：如果原参数未int，也对新参数已浮点数对待（兼容存放int值）
	elif isinstance(example_obj, float):
		return float(var_obj)

	# return None
	return var_obj


# 判断变量类型
def typeof(variate):
	type = None
	if isinstance(variate,int):
		type = "int"
	elif isinstance(variate,str):
		type = "str"
	elif isinstance(variate,float):
		type = "float"
	elif isinstance(variate,list):
		type = "list"
	elif isinstance(variate,tuple):
		type = "tuple"
	elif isinstance(variate,dict):
		type = "dict"
	elif isinstance(variate,set):
		type = "set"
	return type


#########################文件操作相关#########################
#打开log文件
def load_log(log):
	f_s = set()
	if os.path.exists(log):
		with open(log) as indata:
			for line in indata:
				f_s.add(line.strip().split()[0])
	return f_s

def write_into_file(f, content):
	with open(f, 'a+') as f:
		f.write("%s\n" % content)


# 清空文件夹
def clear_folder_shutil(path):
	shutil.rmtree(path)
	os.mkdir(path)


# 检查文件编码，返回结果：：utf-8 或 GB2312
def get_file_encoding(file_path):
    # 读取文件内容
    with open(file_path, 'rb') as f:
        content = f.read()

    # 使用chardet检测文件编码
    result = chardet.detect(content)
    encoding = result['encoding']

    return encoding


#########################计算相关#########################
def square_of_sum(list):
	"""
	求数组各元素的平方和
	:param list:
	:return:
	"""
	return sum([i*i for i in list])


def get_random_int_value(min, max):
	return random.randint(min, max)
